package tech.aistar.day13;

import tech.aistar.day10.Book;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 本类用来演示:
 *
 * @author: success
 * @date: 2021/3/24 2:22 下午
 */
public class ObjectInputStreamDemo {
    public static void main(String[] args) {
        List<Book> books = new ArrayList<>();
        Book b1 = new Book(1,"1001","西游记",100.0d);
        Book b2 = new Book(2,"1002","三体",100.0d);
        books.add(b1);
        books.add(b2);

        writeObj(books,"src/tech/aistar/day13/books2.txt");

        List<Book> list = readList("src/tech/aistar/day13/books2.txt");
        for (Book book : list) {
            System.out.println(book);
        }
    }

    public static void writeObj(List<Book> books,String pathname){
        //1. 构建能够写出对象的字节输出流
        ObjectOutputStream out = null;
        try {
            out = new ObjectOutputStream(new FileOutputStream(pathname));

            out.writeObject(books);

            System.out.println("保存成功!");
        } catch (IOException e) {
            e.printStackTrace();
        }if(null!=out){
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 对象的反序列化
     * @param pathname
     * @return
     */
    public static List<Book> readList(String pathname){
        List<Book> books = null;
        try(ObjectInputStream in = new ObjectInputStream(new FileInputStream(pathname))){
            books = (List<Book>) in.readObject();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return books;
    }
}
